<!DOCTYPE html>
<html>
<head>
    <title>延长已失效限时课程结束日</title>
    <link rel="stylesheet" href="../static/css/minghu.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
</head>
<body>
    {% include 'show_ins_info.html' %}
    <div>
        <h2>延长已失效限时课程结束日</h2>
        <hr>
        <div class="form-row">
            <h4 style="width:80px;margin-right:2px;">会员姓名</h4><input id='cusNameInput' style="width:100px;" oninput="handleCusNameInput()">
        </div>
        <div id="cusList" style="display:none;"></div>
        <!-- <div id="currentClass"></div> -->

        <div class="form-row">
            <h4 style="width:80px;margin-right:2px;">课程类型</h4><select id='clsTypeSel' onchange="generateClsName();getBuyCodeList();"></select>
        </div>


        <div class="form-row">
            <h4 style="width:80px;margin-right:2px;">课程名称</h4><select id='clsNameSel' onchange="getBuyCodeList()"></select>
        </div>

        <div id="cardList" style="margin:10px;padding:8px;border:1px solid rgb(78, 63, 63);border-radius: 4px;line-height: 1.8em;">
            <div>选择需要修改的卡号</div>
            <select id="cardSelect"></select>
            <div id="cardInfo"></div>
        </div>

        <div id='newEndDateBox' class='form-row'  style="display:none;">
            <h4 style="width:70px;margin-right:2px;">新的课程结束日期</h4><input id="newEndDate" type="date" onchange="getNewDateValue();">&nbsp;&nbsp;(不包括该日期)
        </div>

        <button id="submit" onclick="submit()" style="display:none;margin:10px;">修改</button>
        <div id="result" style="display: none;margin:10px;padding:8px;"></div>

        
    </div>

    <script src="../static/js/moment.min.js"></script>
    <script src="../static/js/common.js"></script>
    <script> 
        let cus_list;
        let tmplt_info;
        let cls_types;
        let buy_list;
        let ins_list;
        let insName;
        let insId;
        let insRole;
        let newCardData={};

        // 使用DOMContentLoaded事件监听，在页面加载完成后触发获取数据的操作
        document.addEventListener("DOMContentLoaded", function() {   
            // loginCheck();

            insInfo=hideInsSelectBlockAndGetInsInfo();
            insName=insInfo['sessionInsName'];
            insId=insInfo['sessionInsId'];
            insRole=insInfo['sessionInsRole'];
            
            //教练角色不允许进入该页面，返回Index
            if(insRole==='ins'){
                window.location.replace('./index');
            }else{
                // 只有 LZADM001可以进入该页面
                if(insId!=='LZADM001'){
                    window.location.replace('./index');
                }
            }

            newCardData['ins_id']=insId;

            
            fetch('/get_template_info', {
                method: 'POST',
                headers: {
                    'Content-Type': 'text/plain'
                    }
                })
                .then(response => response.json())
                .then(data => {
            //将data赋值给块变量cus_list，供后面的handleInput使用
                tmplt_info=data;        
                console.log('template infos:',tmplt_info); 
                generateClsType(data['cls_types']);
                document.getElementById('clsTypeSel').dispatchEvent(new Event('change'));
                console.log('cls type sel:',document.getElementById('clsTypeSel').value)
                // Move cls name generation to change event handler
                  })
                .catch(error => console.error('Error:', error));

            fetch('/get_cus_list', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                    }
                })
                .then(response => response.json())
                .then(data => {
            //将data赋值给块变量cus_list，供后面的handleInput使用
                cus_list=data
                // console.log(cus_list);
                  })
                .catch(error => console.error('Error:', error));       
                
            // fetch('/get_ins_list', {
            //     method: 'GET',
            //     headers: {
            //         'Content-Type': 'application/json'
            //         }
            //     })
            //     .then(response => response.json())
            //     .then(data => {
            // //将data赋值给块变量cus_list，供后面的handleInput使用
            //     // ins_list=data
            //     console.log('ins_list:',data)
            //     generateInsList(data.ins_list,'insSelect');
            //     // console.log(cus_list);
            //       })
            //     .catch(error => console.error('Error:', error));    
            const cardListBox=document.getElementById('cardList');
            cardListBox.style.display='none';
            
        });

        function generateClsName(){
            const clsNameSel = document.getElementById('clsNameSel');
            clsNameSel.innerHTML = ''; // Clear existing options
            
            if (!tmplt_info) return;
            
            const selectedType = document.getElementById('clsTypeSel').value;
            const clsNames = tmplt_info['cls_type_name_dic'][selectedType];
            
            if (clsNames) {
                clsNames.forEach(cls => {
                    const opt = document.createElement('option');
                    opt.value = cls;
                    opt.textContent = cls;
                    clsNameSel.appendChild(opt);
                });
            }
        }

        function generateClsType(clsTypes){
            const clsTypeSel=document.getElementById('clsTypeSel');
            clsTypes.forEach(tp=>{
                const opt=document.createElement('option');
                opt.value=tp;
                opt.textContent=tp;
                clsTypeSel.appendChild(opt);
            });
        }
        

        function checkSubmit(){
            const buyCode=document.getElementById('selectBuyCodeContainer').value;
            const startDate=document.getElementById('startDate').value;
            const endDate=document.getElementById('endDate').value;
            const startType=document.querySelector('input[name="startTypeRadio"]:checked').value;
            const insNameSelect=document.getElementById('insSelect').value;
            if(startType==='新课'){
                const compareDate=new Date(endDate)-new Date(startDate);
                    if(compareDate<=0){
                        return '选择的结束日必须在开始日之后';
                    }
            }
            
            // const compareDate=new Date(endDate)-new Date(latestValidEndDate);
            if(buyCode===''||startDate===''||endDate===''){
                
            }
            if(insName==='admin' && insNameSelect===''){
                return '有未选择项目';
            }
            
            
            return 'OK';
        }

        function submit(){
            const result=document.getElementById('result');
            // console.log(newCardData);
            fetch('/edit_pass_due_card_new_end_date',{
                method:"POST",
                headers:{
                    'Content-Type':'application/json'
                },
                body:JSON.stringify(newCardData)
            })
            .then(response=>response.json())
            .then(data=>{
                // console.log(data);
                // location.reload();
                if(data['res']==='ok'){
                    result.innerHTML=`<span style='font-weight:bold;'>新的有效期为</span><br><span style='color:red;'>${dateToStringGmt(data['data']['card_start_time'],'dateDot')} - ${dateToStringGmt(data['data']['end_time'],'dateDot')}</span> （不包括该日期）`;
                    result.style.display='block';
                }else{
                    result.innerHTML='';
                    result.style.display='none';
                }
                
                // window.location.replace('./index');
            })
            .catch(error=>{
                console.error('写入限时课程表或辅助表出错:',error);
                result.innerHTML='';
                result.style.display='none';
            });
           
        }
   
        function dateFormat(inputDate){
            const dateString = inputDate;
            const dateObj = new Date(dateString);
            const formattedDate = toBeijingTimeString(dateObj);
            return formattedDate
        }        

        function getBuyCodeList(cusName=''){
            const sel=document.getElementById('cardSelect');
            const selBox=document.getElementById('cardList');
            const result=document.getElementById('result');
            sel.innerHTML='';
            if(cusName===''){
                cusName=document.getElementById('cusNameInput').value;
            }
            const clsName=document.getElementById('clsNameSel').value;
            const clsType=document.getElementById('clsTypeSel').value;

            fetch('/get_pass_due_rec', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                    },
                body:JSON.stringify({'cus_name':cusName,'cls_name':clsName,'cls_type':clsType})
                })
                .then(response => response.json())
                .then(data => {
                    console.log('pass due data:',data);
                    if(data['res']==='ok'){
                        if(data['data'].length>0){
                            result.innerHTML="";
                            result.style.display='none';
                            generatePassDueList(data['data']);
                        }else{
                            result.innerHTML=`<span style='color:red;'>无匹配的课程</span>`;
                            result.style.display='block';
                            sel.innerHTML='';
                            selBox.style.display='none';
                        }
                        // showCardPrd(data['data']);
                    }else{
                        if(document.getElementById('cusNameInput').value){
                            result.innerHTML="<span style='color:red;'>无匹配的课程</span>";
                            result.style.display='block';
                        }
                        result.innerHTML="";
                        result.style.display='none';
                        
                        sel.innerHTML='';
                        selBox.style.display='none';
                    }
                    
                })                         
                .catch(error => console.error('Error:', error));

            
        }

        function generatePassDueList(data){
            const selBox=document.getElementById('cardList');
            const sel=document.getElementById('cardSelect');

            let dateArr=[]
            data.forEach(item=>{
                if(!dateArr.includes(item[3])){
                    dateArr.push(item[3])
                }
            });

            // 使用自定义比较函数对日期进行降序排列
            dateArr.sort((a, b) => {
                        // 将日期字符串转换为日期对象
                        const dateA=a.slice(3);
                        const dateB=b.slice(3);

                        // 返回比较结果
                        return dateB.localeCompare(dateA);
                        });

            dateArr.forEach(item=>{
                const opt=document.createElement('option');
                opt.text=item;
                opt.value=item;
                sel.appendChild(opt);
            });
            selBox.style.display='block';
            sel.addEventListener('change',function(){
                showCardPrd(data);
            });
            showCardPrd(data);
            

        }

        function showCardPrd(data){
            // console.log('card data:',data);
            const cardId=document.getElementById('cardSelect').value;
            const cardInfo=document.getElementById('cardInfo');
            const editBox=document.getElementById('newEndDateBox');
            const submitBtn=document.getElementById('submit');
            for(i=0;i<data.length;i++){
                if(cardId===data[i][3]){
                    if(data[i][6] && data[i][7]){
                        const today=new Date();
                        const endDate=new Date(data[i][7]);
                        if(endDate<today){
                            cardInfo.innerHTML=`<span style='font-weight:bold;'>有效期</span><br>${dateToStringGmt(data[i][6],'dateDot')} - ${dateToStringGmt(data[i][7],'dateDot')} (不包括该日期)`;
                            showEditBox();
                            newCardData['card_id']=data[i][3];
                            newCardData['cls_type']=data[i][4];
                            newCardData['cls_name']=data[i][5];
                            newCardData['card_start_time']=dateToString(data[i][6],'date');
                            // newCardData['end_time']=data[i][2];
                            newCardData['end_time']=dateToString(document.getElementById('newEndDate').value,'date');
                            newCardData['cls_qty']=data[i][8];
                            newCardData['prd']=data[i][9];
                        }else{
                            cardInfo.innerHTML=`<span style='font-weight:bold;'>有效期</span><br>${dateToStringGmt(data[i][6],'dateDot')} - ${dateToStringGmt(data[i][7],'dateDot')} (不包括该日期)<br><span style="color:green;">卡仍有效</span>`;
                            editBox.style.display='none';
                            submitBtn.style.display='none';
                        }

                        
                    }else{
                        cardInfo.innerHTML=`未开卡`;
                        editBox.style.display='none';
                        submitBtn.style.display='none';
                    } 
                }
            }
        }

        function getNewDateValue(){
            newCardData['end_time']= dateToString(document.getElementById('newEndDate').value,'date');
        }

        function showEditBox(){
            const editBox=document.getElementById('newEndDateBox');
            const submitBtn=document.getElementById('submit');
            editBox.style.display='flex';
            selectToday('newEndDate','date');

            submitBtn.style.display='block';

        }

        function clearItems(){
            document.getElementById('cardSelect').value='';
            document.getElementById('cardList').style.display='none';
            document.getElementById('newEndDateBox').style.display='none';
            document.getElementById('submit').style.display='none';
            document.getElementById('result').innerHTML='';
            document.getElementById('result').style.display='none';

        }

        function handleCusNameInput() {
            //清空
            clearItems();



            // 获取输入框中的值
            const searchTerm = document.getElementById("cusNameInput").value.trim();
            const UpperSearchTerm=searchTerm.toUpperCase();
            // 获取展示结果的列表元素
            const resultList = document.getElementById("cusList");
            const submitButton=document.getElementById('submit');
            // document.getElementById("cusNameBelowDivs").style.display="none";
            // document.getElementById("currentClass").style.display="none";
            submitButton.style.display="none";


            // 清空列表
            resultList.innerHTML = "";

            if (UpperSearchTerm === "") {
                resultList.style.display = "none";
                return; // 输入框为空，不做处理
            }else{
                resultList.style.display = "block";

            }

            // 遍历给定的数组，进行模糊匹配
            cus_list.reverse().forEach(function(name) {
                if (name.includes(UpperSearchTerm)) {
                    // 创建列表项元素，并设置其文本内容为匹配到的结果
                    const listItem = document.createElement("li");
                    listItem.innerText = name;

                    // 添加点击事件监听器
                    listItem.addEventListener("click", function() {
                        // 点击后将完整的姓名设置为输入框的值
                        document.getElementById("cusNameInput").value = name;
     

                        resultList.style.display = "none";
                        // getBuyList(name);
                        getBuyCodeList(name);
                        // 手动触发change事件
                        // nameInput.dispatchEvent(new Event('change'));
                        // 清空结果列表

                        resultList.innerHTML = "";
                    });

                    // 将列表项添加到结果列表中
                    resultList.appendChild(listItem);
                }
            });
        
            resultList.classList.add("cus-list-result-blue");
            // resultList.style.paddingRight='8px';
            resultList.style.top='138px';
            resultList.style.left='218px';
            
        }
     

    </script>
</body>
</html>
